import axios from 'axios'
import {ElMessage} from "element-plus";
import { useRouter } from 'vue-router';
import { useUserStore } from '~/store/useUser';

const baseURL = '/api'

// 添加标志位防止401处理的无限循环
let isLoggingOut = false;

/**
 * @description axios初始化
 */
const instance = axios.create({
    baseURL,
    timeout: 300000, // 超时时间
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    },
})

/**
 * @description axios请求拦截器
 */
instance.interceptors.request.use(requestConf, (error) => {
    return Promise.reject(error)
})

/**
 * @description axios响应拦截器
 */
instance.interceptors.response.use(
    (response) => handleData(response),
    (error) => {
        ElMessage({ message: '网络故障请检查网络', type: 'error', duration: 5000 })
        const { response } = error
        if (response === undefined) {
            return {}
        } else return handleData(response)
    }
)

function requestConf(config) {
    // 请求头 token 处理 - SSR 环境下安全地获取 token
    const token = (typeof window !== 'undefined') ? localStorage.getItem('token') : null
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
}

// config, data, status, statusText
function handleData(res) {
    const { data, status } = res
    //console.log('data is', data)
    if (status !== 200) {
        ElMessage({
            message: `出错了：${res.statusText}`,
            type: 'error',
            duration: 5000,
        })
        return res
    }else{
        if (data && data.code !== 200) {
            if(data.code === 500){
                ElMessage({
                    message: `ERROR:：${data.msg}`,
                    type: 'error',
                    duration: 5000,
                })
            }else{
                if(data.code === 401){
                    // 防止在logout过程中再次触发401处理
                    if (isLoggingOut) {
                        return res;
                    }
                    
                    isLoggingOut = true;
                    const router = useRouter();
                    const userStore = useUserStore();
                    ElMessage({
                        message: data.msg||`登录已过期，请重新登录！`,
                        type: 'error',
                        duration: 5000,
                    })
                    
                    // 直接清除本地存储，不调用logout API避免循环
                    try {
                        if (process.client) {
                            localStorage.removeItem('token');
                            localStorage.removeItem('userInfo');
                        }
                        userStore.userInfo = {};
                        userStore.token = '';
                        router.push("/login");
                    } catch (error) {
                        console.error('清除登录信息失败:', error);
                    } finally {
                        // 重置标志位
                        setTimeout(() => {
                            isLoggingOut = false;
                        }, 1000);
                    }
                    return res
                }
                ElMessage({
                    message: `错误：${data.msg}`,
                    type: 'error',
                    duration: 5000,
                })
            }
        }
        return data
    }
}

export default instance
